package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckItemDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service(interfaceClass = CheckItemService.class)
@Transactional
public class CheckItemServiceImpl implements CheckItemService {

    @Autowired
    CheckItemDao checkItemDao;

    @Override
    public void add(CheckItem checkItem) {
        checkItemDao.add(checkItem);
    }

    @Override
    @Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        //开始分页
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //根据条件查询
        Page<CheckItem> page = checkItemDao.findByCondition(queryPageBean.getQueryString());

        return new PageResult(page.getTotal(), page);
    }

    @Override
    @Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
    public CheckItem findById(Integer id) {
        return checkItemDao.findById(id);
    }

    @Override
    public void update(CheckItem checkItem) {
        checkItemDao.edit(checkItem);
    }

    @Override
    /**
     * 1. 判断检查组是否被检查项所关联(是否在中间表出现)
     * 2. 如果被关联，提示用户不能删除
     * 3. 如果没有关联，直接删除
     */
    public void delById(Integer id) {
        // 1. 判断检查组是否被检查项所关联
        long count = checkItemDao.findCountByCheckItemId(id);
        if(count > 0){
            //2. 如果被关联，提示用户不能删除
            throw new RuntimeException("检查项被检查组关联，不能删除！！");
        }else{
            //3. 如果没有关联，直接删除
            checkItemDao.delById(id);
        }
    }

    @Override
    public List<CheckItem> findAll() {
        return checkItemDao.findAll();
    }
}
